package manageAbilitiesServlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.abilitiesSession.AbilitySessionRemote;

public class ExecuteDecisionOnSuggestAbilityServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		drawPage(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		drawPage(request, response);
	}

	private void drawPage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String decision;
		int idAbility;
		Context jndiCtx;
		idAbility = Integer.parseInt((String) request.getParameter("ida"));
		decision = (String) request.getParameter("decision");
		if (decision != null && decision.length() > 0) {

			try {
				jndiCtx = new InitialContext();
				AbilitySessionRemote abilitySession = (AbilitySessionRemote) jndiCtx
						.lookup("Progetto/AbilitySession/remote");
				if (decision.equals("accept")) {
					// inserisco l'abilita
					if (abilitySession.acceptSuggest(idAbility,
							request.getParameter("suggestedName"),
							request.getParameter("suggestedDescription")))
						request.getSession().setAttribute("result", "commit");
					else
						request.getSession().setAttribute("result", "error");
				} else {
					// cancello la richiesta di abilita
					if (abilitySession.rejectSuggest(idAbility))
						request.getSession().setAttribute("result", "erased");
					else
						request.getSession().setAttribute("result", "error");
				}

			} catch (Exception e) {
				e.printStackTrace();
				request.getSession().setAttribute("result", "error");
			}
			response.sendRedirect("/ProgettoWeb/ManageAbility.html");
		}
	}
}